skip to Main Content

I have a problem to solve. In my canvas image I put a marker but this is image type "png", I would like to have an icon svg so I can change the colour.

This code is working, i need to change .png with .svg, but doesn’t work.

var Marker = function () {

    this.Sprite = new Image();
    this.Sprite.src="http://www.clker.com/cliparts/w/O/e/P/x/i/map-marker-hi.png";
    this.Width = 20;
    this.Height = 32;
    this.XPos = 0;
    this.YPos = 0;
    this.textarea=null;
}

enter image description here

2

Answers


    1. Replace the this.Sprite.src with an SVG image source.

    2. Add a CSS class to the SVG element to apply styling.

    3. Use CSS to change the color of the SVG icon.

    Here’s the modified code:

    var Marker = function () {
        this.Sprite = new Image();
        this.Sprite.src = "your-icon.svg"; // Replace with the path to your SVG icon
        this.Sprite.classList.add("marker-icon"); // Add a CSS class to the SVG element
        this.Width = 20;
        this.Height = 32;
        this.XPos = 0;
        this.YPos = 0;
        this.textarea = null;
    }
    

    In your HTML or CSS, define the marker-icon class and specify the color you want:

    .marker-icon {
        fill: blue; /* Change the fill color to your desired color */
        width: 20px; /* Adjust the width and height as needed */
        height: 32px;
    }
    

    Replace "your-icon.svg" with the path to your SVG icon file, and set the fill property in the CSS class to the color you want for your marker. This way, you can change the color by simply modifying the fill property in your CSS, and you have the flexibility to use SVG icons with different colors.

    I hope that helps

    Login or Signup to reply.
  1. Calling ctx.drawImage on load should do the trick. Drawing SVG files in this manner is supported on all major modern browsers except for IE

    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    
    ...
    
    this.Sprite.onload = function() {
        ctx.drawImage(this.Sprite, 0, 0);
    }
    

    Working jsfiddle

    MDN drawImage docs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search