Bring object to the front in canvas

canvas, javascript, position, z-index

Solution

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/';

Problem

I try to use only one `<canvas>` element 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/

Original source