将图像的裁剪版本绘制到 canvas
drawing a cropped version of an image onto a canvas
我有以下 html 文件,它在 canvas 上绘制图像。
<canvas id="canvas"width="800"height="800"></canvas>
<script>
var canvas = document.getElementById('canvas')
let ctx = canvas.getContext('2d')
let img = new Image()
img.src = 'https://clipartspub.com/images/circle-clipart-blue-1.jpg'
img.onload = function(){
ctx.drawImage(img,300,300,300,300)
}
</script>
它工作正常,但我想绘制此图像的裁剪版本,例如图像的右下四分之一。这可能吗?
您必须使用 drawImage
的以下实现来实现
void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
检查文档 here
var canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let img = new Image();
img.src = "https://clipartspub.com/images/circle-clipart-blue-1.jpg";
img.onload = function () {
const width = img.width;
const height = img.height;
ctx.drawImage(
img, // Source image
width / 2, // Start at this x of image
height / 2, // Start at this y of image
width / 2, // Till this width of image
height / 2, // Till this height of image
0, // Start at this x of canvas
0, // Start at this y of image
300, // Till this width of canvas
300 // // Till this height of canvas
);
};
<canvas id="canvas"width="800"height="800"></canvas>
您还可以在上面使用的 canvas 值中使用 canvas.width
和 canvas.height
以获得更好的缩放结果。
我有以下 html 文件,它在 canvas 上绘制图像。
<canvas id="canvas"width="800"height="800"></canvas>
<script>
var canvas = document.getElementById('canvas')
let ctx = canvas.getContext('2d')
let img = new Image()
img.src = 'https://clipartspub.com/images/circle-clipart-blue-1.jpg'
img.onload = function(){
ctx.drawImage(img,300,300,300,300)
}
</script>
它工作正常,但我想绘制此图像的裁剪版本,例如图像的右下四分之一。这可能吗?
您必须使用 drawImage
的以下实现来实现
void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
检查文档 here
var canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let img = new Image();
img.src = "https://clipartspub.com/images/circle-clipart-blue-1.jpg";
img.onload = function () {
const width = img.width;
const height = img.height;
ctx.drawImage(
img, // Source image
width / 2, // Start at this x of image
height / 2, // Start at this y of image
width / 2, // Till this width of image
height / 2, // Till this height of image
0, // Start at this x of canvas
0, // Start at this y of image
300, // Till this width of canvas
300 // // Till this height of canvas
);
};
<canvas id="canvas"width="800"height="800"></canvas>
您还可以在上面使用的 canvas 值中使用 canvas.width
和 canvas.height
以获得更好的缩放结果。