Domanda

I try to use only one <canvas> element

enter image description here

1 : Clip a image

2 : Make one more rectangle

But How to bring that rectangle to the front ?


var canvas = document.getElementById('example');
var ctx = canvas.getContext('2d');
var image = document.createElement('IMG');
image.onload = function () {
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(29, 96);
    ctx.lineTo(157, 0);
    ctx.lineTo(288, 93);
    ctx.closePath();
    ctx.clip();
    ctx.drawImage(image, 0, 0);
    ctx.restore();
};
image.src = 'http://lorempixel.com/500/500/';



// This

ctx.rect(20,20,150,100);
ctx.fillStyle="red";
ctx.fill();

Demo : http://jsfiddle.net/yW86d/

È stato utile?

Soluzione

draw the rectangle after image has been drawn

i modified your code. try this,

var canvas = document.getElementById('example');
var ctx = canvas.getContext('2d');
var image = document.createElement('IMG');
image.onload = function () {
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(29, 96);
    ctx.lineTo(157, 0);
    ctx.lineTo(288, 93);
    ctx.closePath();
    ctx.clip();
    ctx.drawImage(image, 0, 0);
    ctx.restore();

    ctx.beginPath();
    ctx.rect(20,20,150,100);
    ctx.fillStyle="red";
    ctx.fill();
};
image.src = 'http://lorempixel.com/500/500/';

Altri suggerimenti

In JavaScript canvas the last element drawn is on top, thus you cant use z-index to arrange your elements, you just have to draw them in the order you want them to appear. For example if you want an element to be all the way in the back - draw it first, and if you want an element to be on top of every other element - draw it last.

Your code will look something like:

var canvas = document.getElementById('example');
var ctx = canvas.getContext('2d');
var image = document.createElement('IMG');
image.src = 'http://lorempixel.com/500/500/';


ctx.rect(20,20,150,100);
ctx.fillStyle="red";
ctx.fill();
image.onload = function () {
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(29, 96);
        ctx.lineTo(157, 0);
        ctx.lineTo(288, 93);
        ctx.closePath();
        ctx.clip();
        ctx.drawImage(image, 0, 0);
        ctx.restore();
};

The image is drawn after the rectangle, so its on top :)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top