如何通过javascript识别画布中的区域 [英] How to recognize an area in an canvas via javascript

查看:185
本文介绍了如何通过javascript识别画布中的区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此图片加载到html5画布中。



如果用户在广场内的任何一点按下,我想用颜色填充此区域。但就在里面,颜色停在黑线。你可以考虑像Windows Paint中的填充工具。



我如何解决这个问题?有这样的功能的JavaScript有开始吗?



解决方案

您可能需要使用 CanvasRenderingContext2D.isPointInPath()



  var canvas = document.getElementById(canvas); var ctx = canvas.getContext(2d); ctx.clicked = false; function draw(){ctx.clearRect(0,0,canvas.width,高度); ctx.save(); (45); ctx.beginPath(); ctx.rect(100,-100,100,100); if(ctx.clicked){ctx.fillStyle =blue; ctx.fill()} ctx.stroke(); ctx.restore();} draw(); canvas.addEventListener('click',function(e){var bounds = canvas.getBoundingClientRect(); var mouseXY = [e.clientX-bounds.left,e.clientY-bounds .top] ctx.clicked = ctx.isPointInPath(mouseXY [0],mouseXY [1]); draw();});    canvas {border:1px solid}  

 < canvas id =canvasheight =500width =500>< / canvas>  


This image is loaded in an html5 canvas.

If a user presses at any point inside the square, I want to fill this area with a color. But just inside, the color stops at the black lines. You can think about the fill tool like in Windows Paint.

How can I solve this? Are there libraries for javascript for such a function to start with?

解决方案

You might want to use the CanvasRenderingContext2D.isPointInPath()

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.clicked = false;

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.save();
  ctx.rotate(45);
  ctx.beginPath();
  ctx.rect(100, -100, 100, 100);
  if (ctx.clicked) {
    ctx.fillStyle = "blue";
    ctx.fill()
  }
  ctx.stroke();
  ctx.restore();
}
draw();
canvas.addEventListener('click', function(e) {
  var bounds= canvas.getBoundingClientRect();
  var mouseXY = [e.clientX-bounds.left, e.clientY-bounds.top]
  ctx.clicked = ctx.isPointInPath(mouseXY[0], mouseXY[1]);
  draw();
});

canvas {
  border: 1px solid
}

<canvas id="canvas" height="500" width="500"></canvas>

这篇关于如何通过javascript识别画布中的区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆