简体   繁体   English

如何在画布上的不寻常形状上绘制网格

[英]How to draw a grid over an Unusual shape on canvas

I am trying to work out a way to draw a grid over a png image so that the grid only is drawn on parts of the image. 我正在尝试找出一种在png图像上绘制网格的方法,以便仅在图像的一部分上绘制网格。

I do not want the grid on any parts of the page that is not the shape. 我不希望页面上任何不是形状的部分都带有网格。

How do you do this? 你怎么做到这一点?

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(75, 50);
ctx.lineTo(40, 205);
ctx.lineTo(300, 25);
ctx.fillStyle = 'green';
ctx.fill();


function drawGrid(context) {
  context.globalCompositeOperation = 'destination-out   ';

  for (var x = 40.5; x < 300; x += 10) {
    context.moveTo(x, 0);
    context.lineTo(x, 300);
  }

  for (var y = 0.5; y < 301; y += 10) {
    context.moveTo(0, y);
    context.lineTo(300, y);
  }

  context.strokeStyle = "#ddd";
  context.stroke();
}

drawGrid(ctx)

https://jsfiddle.net/m8679fk4/2/ https://jsfiddle.net/m8679fk4/2/

First, change your composite operation to destination-out and furthermore put the call to drawGrid(context); 首先,将复合操作更改为目的地输出 ,然后将调用置于drawGrid(context);中。 into the onload handler, right after context.drawImage(img, 0, 0); 紧跟context.drawImage(img,0,0)进入onload处理程序 - otherwise the grid might get drawn before the image even finished loading. -否则,在图像加载完成之前可能会绘制网格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM