canvas drawImage() - 将图像切成两半并取左边部分
canvas drawImage() - cut image in half and take left part
使用的图片:https://i.imgur.com/5KYZ1M2.jpg
代码:
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(media, canvas.width / 2, 0, canvas.width, canvas.height);
有没有办法只获取左图并居中?
我在Codepen中做了一个例子,canvas元素是图像宽度的一半,然后图像左对齐和上对齐。 ctx.drawImage(img, 0, 0);
你应该使用 drawImage
的可选参数,这样你的 canvas 可以是任何大小,所以它应该是:
context.drawImage( media, 0, 0, media.width / 2, media.height, 0, 0, canvas.width, canvas.height);
var my_canvas = document.getElementById('canvas'),
context = my_canvas.getContext("2d");
let media = new Image();
media.src = 'https://i.imgur.com/5KYZ1M2.jpg';
media.onload = function() {
context.drawImage( media, 0, 0, media.width / 2, media.height, 0, 0, canvas.width, canvas.height);
}
canvas {
border: 1px dotted black;
width: 200px;
height: 200px;
}
<canvas id="canvas" width="200" height="200">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
您可以阅读有关 drawImage
here
的更多信息
使用的图片:https://i.imgur.com/5KYZ1M2.jpg
代码:
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(media, canvas.width / 2, 0, canvas.width, canvas.height);
有没有办法只获取左图并居中?
我在Codepen中做了一个例子,canvas元素是图像宽度的一半,然后图像左对齐和上对齐。 ctx.drawImage(img, 0, 0);
你应该使用 drawImage
的可选参数,这样你的 canvas 可以是任何大小,所以它应该是:
context.drawImage( media, 0, 0, media.width / 2, media.height, 0, 0, canvas.width, canvas.height);
var my_canvas = document.getElementById('canvas'),
context = my_canvas.getContext("2d");
let media = new Image();
media.src = 'https://i.imgur.com/5KYZ1M2.jpg';
media.onload = function() {
context.drawImage( media, 0, 0, media.width / 2, media.height, 0, 0, canvas.width, canvas.height);
}
canvas {
border: 1px dotted black;
width: 200px;
height: 200px;
}
<canvas id="canvas" width="200" height="200">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
您可以阅读有关 drawImage
here