html5 fill,javascript - HTML5 Canvas - How to fill() a specific context - Stack Overflow

I'm trying to make a website where an image is drawn on Canvas, then later the user is able to press a button to ctx.fill() certain parts of it with color. I'm running into issues where I can only ctx.fill() the most recently created shape which often isn't the shape I want.

Here's an example. In this code (live at http://build.rivingtondesignhouse.com/piol/test/) I'm trying to draw the first rectangle, then save() it on the stack, then draw the second rectangle (and don't save it), then when my fill() function is called I want to restore() the first rectangle and ctx.fill() it with a different pattern. It doesn't work!

In practice, I'm actually trying to fill the gray part of this complex shape with any color the user chooses AFTER the image has been drawn, but I think the technique is the same. (http://build.rivingtondesignhouse.com/piol/test/justTop.html)

Thanks in advance for any help!!!

Here's the code:

var canvas;

var ctx;

function init() {

canvas = document.getElementById("canvas");

ctx = canvas.getContext("2d");

draw();

}

function draw() {

ctx.fillStyle = '#FA6900';

ctx.shadowOffsetX = 5;

ctx.shadowOffsetY = 5;

ctx.shadowBlur = 4;

ctx.shadowColor = 'rgba(204, 204, 204, 0.5)';

ctx.fillRect(0,0,15,150);

ctx.save();

ctx.fillStyle = '#E0E4CD';

ctx.shadowOffsetX = 10;

ctx.shadowOffsetY = 10;

ctx.shadowBlur = 4;

ctx.shadowColor = 'rgba(204, 204, 204, 0.5)';

ctx.fillRect(30,0,30,150);

}

function fill(){

var image = new Image();

image.src = "http://www.html5canvastutorials.com/demos/assets/wood-pattern.png";

image.onload = drawPattern;

function drawPattern() {

ctx.restore();

ctx.fillStyle = ctx.createPattern(image, "repeat");

ctx.fill();

}

}

init();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值