html5 css background,HTML5 Canvas as CSS background-image?

问题

Is it possible to make the background image of a DIV a canvas that can be modified with getContext("2d")?

回答1:

You can have a canvas inside the div with absolute css position, other elements have to have z-index greater than the canvas.

回答2:

Well, you could place a canvas element inside of the div, maximize its height and width, set its position to relative and its z-index to a negative value.

However, if you want to use a real CSS background-image:... you would have to create your image inside your canvas. You could then use toDataURL to get a data url which you could use as value for your original background-image:

var canvas = document.getElementById('canvas');

var data = canvas.toDataURL();

var myElement = document.getElementById('myelement');

myElement.style.backgroundImage = 'url('+data+')';

If you don't want to create a new background but manipulate an existing one, load your original background into an Image object (or get a reference) and use drawImage:

var image = new Image();

image.onload = function(){

context.drawImage(this,0,0);

someCallbackToManipulateTheImage();

}

var src = myElement.style.backgroundImage.substr(4);

src.substr(0,src.length - 1);

image.src = src;

回答3:

Set the background-image of the div to this:

"url('" + canvas.toDataURL() + "')";

Edit: At that point, note that you are also free to do what you wish with the canvas, as the background-image will continue to contain only the image data that was in the canvas at the moment that you called canvas.toDataURL(). Feel free to discard or draw onto the canvas, as it will not affect your div's background at that point.

来源:https://stackoverflow.com/questions/9971249/html5-canvas-as-css-background-image

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值