在开始讲解技术细节之前请先看这个,输入任意的图像URL,然后点击 Img2Canvas 按钮
BTW: 同样接受 data-uri 格式数据。
代码:
function draw() { // Get the canvas element and set the dimensions. var canvas = document.getElementById('canvas'); canvas.height = window.innerHeight; canvas.width = window.innerWidth; // Get a 2D context. var ctx = canvas.getContext('2d'); // create new image object to use as pattern var img = new Image(); img.src = document.getElementById('url').value; img.onload = function(){ // Create pattern and don't repeat! var ptrn = ctx.createPattern(img,'no-repeat'); ctx.fillStyle = ptrn; ctx.fillRect(0,0,canvas.width,canvas.height); } }应用逻辑:
关键的地方在于 createPattern()
nsIDOMCanvasPattern createPattern(in nsIDOMHTMLElement image, in DOMString repetition);
context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");