如何将div背景设置为canvs

时间:2015-05-21 06:16:52

标签: javascript html css canvas

这是我的代码:

<!DOCTYPE html>
<html>
    <body>
        <div id='rect' style='width:200px;height:200px;border:1px solid red'>
        </div>
        <canvas id="myCanvas" style="border:1px solid #d3d3d3;">    
        <script>
            patternStyle = document.getElementById("myCanvas");
            var patternContext = patternStyle.getContext('2d');
            patternStyle.width = 6;
            patternStyle.height = 6;
            patternContext.globalAlpha = 10;
            patternContext.fillStyle = 'white';
            patternContext.rect(0, 0, 6, 6);
            patternContext.fillRect(0, 0, 6, 6);
            patternContext.strokeStyle = 'red';
            patternContext.lineWidth = 2;
            patternContext.beginPath();
            patternContext.moveTo(3, -3);
            patternContext.lineTo(-3, 3);
            patternContext.moveTo(0, 6);
            patternContext.lineTo(6, 0);
            patternContext.moveTo(9, 3);
            patternContext.lineTo(3, 9);
            patternContext.stroke();
        </script> 
    </body>
</html>

我需要将rect(id of the div)背景图片设置为myCanvas(id of the canvas)。我怎样才能做到这一点?

在此处找到jsfiddle链接:http://jsfiddle.net/yLL48one/

1 个答案:

答案 0 :(得分:1)

查看更新后的小提琴:http://jsfiddle.net/yLL48one/1/

关键是:

dataUrl = document.getElementById('myCanvas').toDataURL();
document.getElementById('rect').style.background='url('+dataUrl+')';