【发布时间】:2022-10-08 22:09:31
【问题描述】:
我找到了一个很好的解决方案并对其进行了编辑,因此您只需更改画布的大小,图像仍然会对齐。 x_move 和 y_move 变量确定显示图像的哪个部分
var myImage = new Image();
var size = myCanvas.width;
var x_move = -35;
var y_move = 0;
function displayImage() {
canvas = document.getElementById("myCanvas");
if (canvas.getContext) {
ctx = canvas.getContext("2d");
myImage.onload = function() {
ctx.drawImage(myImage, x_move, y_move, (myImage.width / (myImage.height / size)) , size );
ctx.strokeStyle = "white";
ctx.lineWidth = (size/2).toString();
ctx.beginPath();
ctx.arc(size/2, size/2, size*0.75, 0, Math.PI * 2, true);
ctx.closePath();
ctx.stroke();
}
myImage.src = "https://i1.wp.com/nypost.com/wp-content/uploads/sites/2/2016/09/astley1_index1a.jpg";
}
}
<!DOCTYPE html>
<html>
<body onload="displayImage()">
<canvas id="myCanvas" width="200" height="200">
</canvas>
</body>
</html>
原始代码:
https://www.authorcode.com/show-image-into-a-circle-shape-in-html5/
【讨论】: