HTML5 Canvas as CSS background-image?

后端 未结 3 1110
闹比i
闹比i 2021-01-05 00:23

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

相关标签:
3条回答
  • 2021-01-05 00:35

    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;
    
    0 讨论(0)
  • 2021-01-05 00:37

    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.

    0 讨论(0)
  • 2021-01-05 00:52

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

    0 讨论(0)
提交回复
热议问题