我创建了一个画布,例如有4个单元格,如何为每个单元格设置图像?我的Canvas旋转了,我也不想图像也旋转,当鼠标在单元格上移动时,图像也消失了!
我的代码:
<html>
<head>
<script src="jquery-3.4.1.js"></script>
</head>
<body bgcolor="black">
<canvas id="tutorial" width="500" height="500"></canvas>
<script type="text/javascript">
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d"),
rects = [
{x: 0, y: 0, w: 100, h: 100},
{x: 0, y: 100, w: 100, h: 100},
{x: 100, y: 100, w: 100, h: 100},
{x: 100, y: 0, w: 100, h: 100}
], i = 0, r;
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.scale(0.71, 0.3834);
ctx.rotate(-0.25 * Math.PI);
// render initial rects.
while(r = rects[i++]) ctx.rect(r.x, r.y, r.w, r.h);
// var img = new Image();
// img.onload = function () {
// ctx.drawImage(img, 0, 0);
// }
// img.src = "i1.png";
ctx.fillStyle = "#c5de89";
ctx.fill();
canvas.onmousemove = function(e) {
var rect = this.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top,
i = 0, r;
ctx.clearRect(0, 0, canvas.width, canvas.height);
while(r = rects[i++]) {
ctx.beginPath();
ctx.rect(r.x, r.y, r.w, r.h);
ctx.fillStyle = ctx.isPointInPath(x, y) ? "red" : "#c5de89";
ctx.fill();
}
};
</script>
</body>
</html>
我想要这样的东西:
我的画布:
您还应该在onmousemove函数中添加图像x和y坐标,因为您正在该函数中重建画布。
var angle = 0;
var canvas = document.getElementById("tutorial"),
ctx = canvas.getContext("2d"),
rects = [{
x: 0,
y: 0,
w: 100,
h: 100
},
{
x: 0,
y: 100,
w: 100,
h: 100
},
{
x: 100,
y: 100,
w: 100,
h: 100
},
{
x: 100,
y: 0,
w: 100,
h: 100
}
],
i = 0,
r;
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.scale(0.71, 0.3834);
ctx.rotate(-0.25 * Math.PI);
// render initial rects.
while (r = rects[i++]) {
ctx.rect(r.x, r.y, r.w, r.h);
ctx.fillStyle = "#c5de89";
ctx.fill();
ctx.save();
ctx.rotate(0.25 * Math.PI);
base_image = new Image();
base_image.src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
ctx.drawImage(base_image, r.x, r.y - 75);
ctx.restore()
}
canvas.onmousemove = function(e) {
var rect = this.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top,
i = 0,
r;
ctx.clearRect(0, 0, canvas.width, canvas.height);
while (r = rects[i++]) {
ctx.beginPath();
ctx.rect(r.x, r.y, r.w, r.h);
ctx.fillStyle = ctx.isPointInPath(x, y) ? "red" : "#c5de89";
ctx.fill();
ctx.save();
ctx.rotate(0.25 * Math.PI);
base_image = new Image();
base_image.src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
ctx.drawImage(base_image, r.x, r.y - 100);
ctx.restore()
}
};
<html>
<head>
<script src="jquery-3.4.1.js"></script>
</head>
<body bgcolor="black">
<canvas id="tutorial" width="500" height="500"></canvas>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句