0

hi I want to rotate my PNG with this code below :

async function rotateImage(imageBase64, rotation) {
        var img = new Image();
        img.src = imageBase64;
        return new Promise(resolve => {
            img.onload = () => {
                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                canvas.width = img.width;
                canvas.height = img.height;

                ctx.fillStyle = "rgba(255,255,255,.6)";
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                ctx.save();

                ctx.translate(canvas.width / 2, canvas.height / 2)
                ctx.rotate(rotation * (Math.PI / 180));

                ctx.drawImage(img, -img.width / 2, -img.height / 2);

                ctx.restore();
                resolve(canvas.toDataURL("image/jpeg"))
            };
        })

this is my image before rotate : before rotate and this is my image after rotate: after rotate after rotate background corners of image is black how to transparent? NOTE: I use this PNG for marker of google map. I read this posts :

Canvas fillStyle none in HTML5

Transparency context.fill style in canvas html5

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

thanks for helping.

iamir4g
  • 1
  • 1
  • I think this line is the problem `ctx.fillStyle = "rgba(255,255,255,.6)";`, you are filling the canvas with a gray colour – PeterSH Sep 15 '20 at 07:09
  • if delete this line background is black – iamir4g Sep 15 '20 at 07:25
  • And if you set it to `ctx.fillStyle = "transparent"` or `ctx.fillStyle = "rgba(255,255,255,0)"`? – PeterSH Sep 15 '20 at 07:40
  • You are converting the image to an JPEG encoded url. JPEG format does not include transparency (alpha channel). Use `canvas.toDataURL("image/png")` if you want to keep the alpha channel – Blindman67 Sep 15 '20 at 10:27
  • @Blindman67 yeeeesss, thank alot,I did not pay attention to this point at all, thank thank – iamir4g Sep 15 '20 at 11:38

0 Answers0