javascript - 使用 javascript 和 css 在图像上叠加可点击的点状图案

标签 javascript css html5-canvas processing

<分区>


想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post .

关闭 8 年前

我想使用 javascript 和 css 在图像上实现可点击的点状图案叠加,但不知道从哪里开始。每个点都有一个可点击的 url,该 url 是唯一的并以编程方式分配。如果有人能指出正确的方向,我将不胜感激 :) 谢谢。

原文:

Original

结果:

enter image description here

最佳答案

您可以使用合成来创建点状图像。

虚线图效果:

enter image description here

  • 用黑色填充 Canvas
  • 将合成设置为 destination-out,这将导致新绘图“删除”现有(黑色)内容。
  • 在行和列中画点。每个点都会去掉其下方的黑色,使该点透明。
  • 将合成设置为 destination-atop,这将使新绘图仅绘制在 Canvas 的透明部分上。
  • 绘制图像。图像只会以点的形式出现。

响应对特定点的点击

  • 监听 mousedown 事件。
  • 计算用户点击了哪个点。
  • 将用户带到与该标识点相对应的 URL。

这是示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
  var BB=canvas.getBoundingClientRect();
  offsetX=BB.left;
  offsetY=BB.top;        
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }


var PI2=Math.PI*2;
var radius=5;
var spacer=1;
var diameter=radius*2;

var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/dotimage.jpg";
function start(){
  cw=canvas.width=img.width;
  ch=canvas.height=img.height;
  //
  ctx.fillStyle='black';
  ctx.fillRect(0,0,cw,ch);
  //
  ctx.globalCompositeOperation='destination-out';
  ctx.beginPath();
  for(var y=radius;y<ch;y+=diameter+spacer){
    for(var x=radius;x<cw;x+=diameter+spacer){
      ctx.arc(x,y,radius,0,PI2);
      ctx.closePath();
    }}
  ctx.fill();
  //
  ctx.globalCompositeOperation='destination-atop';
  ctx.drawImage(img,0,0);
  //
  ctx.globalCompositing='source-over';
}



function handleMouseDown(e){
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  mouseX=parseInt(e.clientX-offsetX);
  mouseY=parseInt(e.clientY-offsetY);

  //
  var x=parseInt(mouseX/(diameter+spacer));
  var y=parseInt(mouseY/(diameter+spacer));
  $('#position').text('You clicked dot at x='+x+' / y='+y);

}


$("#canvas").mousedown(function(e){handleMouseDown(e);});
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4 id=position>Click on a dot.</h4>
<canvas id="canvas" width=300 height=300></canvas>

关于javascript - 使用 javascript 和 css 在图像上叠加可点击的点状图案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30510731/

上一篇:css - 能够仅在 CSS 中回滚菜单

下一篇:javascript - Uncaught ReferenceError : google is not defined (Google Chart)

相关文章:

javascript - Google map - 使用多个标记时,信息窗口中会显示相同的文本

php - 总是返回字母数字字符?

javascript - 如何在 IE11 中提供 document.all

javascript - 如果未登录,则限制对 js 文件的访问

jquery - 当屏幕较小时,有没有办法控制我的div在class =“row”内的垂直对齐方式

html - 针对每个 parent 的所有其他 child

javascript - pdf.js 在 getDocument 上失败

node.js - HTML5视频录制

javascript - 动态调整 iframe 的大小

javascript - 如何使用 javascript 在 Canvas 中绘制压缩文本?