make clickable region in canvas to change image(在画布中制作可点击区域以更改图像)
问题描述
请帮帮我:
在下面的画布中创建可点击区域,我可以将 onmousedown= 事件分配给这些区域.我知道如何用不可见的 DIV 做到这一点,但我认为有一种更优雅的方式可以在我不知道的画布中做到这一点.
create clickable regions in the canvas below that I can assign onmousedown= events to. I know how to do this with invisible DIVs, but I think there is a more elegant way to do it in canvas that I don't know.
当我单击其中一个区域时,想要将图像名称传递给函数,以便它将正在显示的图像更改为另一个图像,然后将其更改回 onmouseup.
when I click one of the regions, want to pass an image name to a function so that it changes the image being displayed to another image, and then changes it back onmouseup.
如果您只给我展示一个区域和一个 mousedown/mouseup 示例,我可以完成剩下的...谢谢.
if you show me just one region and one mousedown/mouseup example I can do the rest...thanks.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="506" height="319" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
};
img.src="firstImage.gif";
</script>
/////////HERE NEED/////////
CREATE CLICKABLE REGION <region>
<region>
onmousedown=changeCanvasImage(secondImage.gif) //change image on click
onmouseup=changeCanvasImage(firstImage.gif) /change it back when done
</region>
</body>
</html>
推荐答案
canvas 元素可以触发事件,但canvas 中的图形元素不能.为此,您需要通过检测 鼠标在画布上的位置,当它被单击并将值与画布中的某些内容相关联时,或者使用许多 canvas 库可用于处理为您检测.
The canvas element can fire events but graphical elements within the canvas cannot. To do this you'll either need to implement it yourself by detecting the position of the mouse on the canvas when it is clicked and relating the value to something in your canvas, or using one of the many canvas libraries available which will handle the detection for you.
这篇关于在画布中制作可点击区域以更改图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在画布中制作可点击区域以更改图像
基础教程推荐
- Chart.js 在线性图表上拖动点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01