A recent project needs to support multi-terminal, and the webpage version needs to use canvas canvas object in HTML5 to render and restore a group of data. However, there is a problem in the actual implementation process, canvas does not have the concept of mask layer, so some effects cannot be realized. When we finally look at the documentation, we see that the mask can be implemented either through the Context object’s globalCompositeOperation property or through the Context’s Clip () clipping path method.

GlobalCompositeOperation properties#

Let’s take a closer look at the various value descriptions of the Context’s globalCompositeOperation, which we used to achieve a scratch-card effect because it was too difficult to demonstrate.

Attribute values describe According to the effect
source-over (default) The new graphics will be overlaid on top of the original content
destination-over New graphics will be drawn under the original content
source-in The new graphics will only appear where they overlap with the original content. Everything else becomes transparent
destination-in Parts of the original content that overlap with the new graphics will be retained, and other areas will become transparent
source-out The result is that only parts of the new graph that do not overlap with the original content will be drawn
destination-out Parts of the original content that do not overlap with the new graphics will be retained
source-atop Portions of the new graphic that overlap with the original content are drawn and overlaid on top of the original content
destination-atop Parts of the original content that overlap with the new content will be retained, and new graphics will be drawn under the original content
lighter The overlapping part of the two figures is treated with additive color
darker The overlapping part of two figures is subtracted
xor The overlap will become transparent
copy Only new shapes are retained, everything else is cleared

Blue represents the graph drawn first, red represents the graph drawn later

Browser support: Internet Explorer 9, Firefox, Opera, Chrome, and Safari support the globalCompositeOperation attribute

With Context’s globalCompositeOperation we can flexibly master the hierarchical display relationship between graphics to make a lot of beautiful display effects. Next we implement a scratch card effect using globalCompositeOperation= destination-Out.

The globalCompositeOperation property is applied#

Scratch card implementation renderings

Canvas achieves scratch card effect

Realize the principle of

  1. Put one on the pagedivContainer, set the width and height of the divdoraemonAs the background,
  2. Put one in divcanvasTag, set to canvasWide highSame as the parent container div.
  3. Get the Canvas context object and draw a gray rectangle with the same width and height as the canvas, so that the Robocat background is obscured and only a gray background can be seen.
  4. Canvas binding mouse mousedown, mousemove and mouseup events (mobile terminal binding events are: touchstart, touchmove, touchend), set up the mouse to press the sign, the mouse click or mouse click move and record the mouse coordinates.
  5. Mouse click or hold down mouse movement to start drawing, drawing while settingcontext.globalCompositeOperation='destination-out'According to the explanation of the above attributes, the non-overlapping part of the original graph (gray rectangle) and the new graph (drawn lines) will be retained, so the part with drawn lines will not be retained and the following doraemon picture background can be seen.
  6. Mouse up Sets the mouse down flag to false and clears the coordinate array.

Specific code

HTML code (canvas dynamically created)

<div id='div' style='width:540px; min-height:360px; background:url(".. /images/test.jpg") no-repeat'> </div>Copy the code

Javascript code

function init() { if (! document.getElementById("myCanvas")) { var width = ""; var height = ""; var canvas = document.createElement("canvas"); width = document.getElementById("div").offsetWidth; height = document.getElementById("div").offsetHeight; canvas.setAttribute("width", width + "px"); canvas.setAttribute("height", height + "px"); canvas.setAttribute("style", "border:1px solid green"); canvas.id = "myCanvas"; document.getElementById("div").appendChild(canvas); } var myCanvasObject = document.getElementById("myCanvas"); var ctx = myCanvasObject.getContext("2d"); // Draw a black rectangle ctx.beginPath(); ctx.fillStyle = "#939393"; ctx.rect(0, 0, width, height); ctx.closePath(); ctx.fill(); var isDown = false; Var pointerArr = []; Var xPointer = 0; Var yPointer = 0; Var hastouch = "ontouchstart" in window? true : false, tapstart = hastouch ? "touchstart" : "mousedown", tapmove = hastouch ? "touchmove" : "mousemove", tapend = hastouch ? "touchend" : "mouseup"; / / mouse press myCanvasObject. AddEventListener (tapstart, function (event) {this. Style. Cursor = "move"; isDown = true; xPointer = hastouch ? e.targetTouches[0].pageX : e.clientX - this.offsetLeft; yPointer = hastouch ? e.targetTouches[0].pageY : e.clientY - this.offsetTop;; pointerArr.push([xPointer, yPointer]); circleReset(ctx); }); / / mouse drag myCanvasObject. After pressing the addEventListener (tapmove, function (event) {if (isDown) {xPointer = hastouch? e.targetTouches[0].pageX : e.clientX - this.offsetLeft;; yPointer = hastouch ? e.targetTouches[0].pageY : e.clientY - this.offsetTop;; pointerArr.push([xPointer, yPointer]); circleReset(ctx); }}); / / mouse took up the cancellation event myCanvasObject. AddEventListener (tapend, function (event) {isDown = false; pointerArr = []; }); Function circleReset(CTX) {ctx.save(); ctx.beginPath(); ctx.moveTo(pointerArr[0][0], pointerArr[0][1]); CTX. LineCap = "round"; CTX. LineJoin = "round"; // Set line transition to arc ctx.lineWidth = 60; ctx.globalCompositeOperation = "destination-out"; if (pointerArr.length == 1) { ctx.lineTo(pointerArr[0][0] + 1, pointerArr[0][1] + 1); } else { for (var i=1; i<pointerArr.length; i++) { ctx.lineTo(pointerArr[i][0], pointerArr[i][1]); ctx.moveTo(pointerArr[i][0], pointerArr[i][1]); } } ctx.closePath(); ctx.stroke(); ctx.restore(); }}Copy the code

Reference documentation#

Canvas reference document Canvas API







If this article is wrong, please feel free to comment!

The implementation method of mask effect in Canvas

The original link: www.mengxiangjia.info/2015/12/31/…

Copyright statement: free reproduced signature – not commercial – not derivative – keep | Creative Commons BY – NC – ND 3.0