简体   繁体   中英

How can I put Javascript element into CSS background-image

Hi my first javascript project. I wanted to create image in javascript and put it as background for the clock created in css. Everything works great but I don't know how to refer to css.clock so I could put drawn image as background to my css clock (4th line in css file).

I saw other questions but they mostly refer to other javascript drawn images. I want to either add myPiechart.draw as background for css clock or save it as image and set is as background for css clock. Whichever is easier to do. Here you have code below if you copy paste you will see working clock and created image:

html file:

<!DOCTYPE html>

<head>
  <link href="styles.css" rel="stylesheet">
  <script defer src="script.js"></script>
</head>

<body>
  <div class="clock">
    <div class="hand hour" data-hour-hand></div>
    <div class="hand minute" data-minute-hand></div>
    <div class="hand second" data-second-hand></div>
  </div>
  <canvas id="myCanvas"></canvas>
  <script type="text/javascript" src="script.js"></script>
</body>

</html>

javascript file (creating image that I want to be added as background):

var myCanvas = document.getElementById("myCanvas");
myCanvas.width = 300;
myCanvas.height = 300;

var ctx = myCanvas.getContext("2d");

// FUNCTIONS FOR DRAWING CHART
function drawLine(ctx, startX, startY, endX, endY) {
  ctx.beginPath();
  ctx.moveTo(startX, startY);
  ctx.lineTo(endX, endY);
  ctx.stroke();
}

function drawArc(ctx, centerX, centerY, radius, startAngle, endAngle) {
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, startAngle, endAngle);
  ctx.stroke();
}

function drawPieSlice(ctx, centerX, centerY, radius, startAngle, endAngle, color) {
  ctx.fillStyle = color;
  ctx.beginPath();
  ctx.moveTo(centerX, centerY);
  ctx.arc(centerX, centerY, radius, startAngle - 1.575, endAngle - 1.575);
  ctx.closePath();
  ctx.fill();
}

// FUNCTION THAT DRAWS PIE CHART
var Piechart = function (options) {
  this.options = options;
  this.canvas = options.canvas;
  this.ctx = this.canvas.getContext("2d");
  this.colors = options.colors;

  this.draw = function () {
    var total_value = 0;
    var color_index = 0;
    for (var categ in this.options.data) {
      var val = this.options.data[categ];
      total_value += val;
    }

    var start_angle = 0;
    for (categ in this.options.data) {
      val = this.options.data[categ];
      var slice_angle = (2 * Math.PI * val) / total_value;

      drawPieSlice(
        this.ctx,
        this.canvas.width / 2,
        this.canvas.height / 2,
        Math.min(this.canvas.width / 2, this.canvas.height / 2),
        start_angle,
        start_angle + slice_angle,
        this.colors[color_index % this.colors.length]
      );

      start_angle += slice_angle;
      color_index++;
    }
  };
};

// DATA
var myData = {
  "A": 15,
  "B": 25,
  "C": 12,
  "D": 8,
};

// CREATING NEW PIECHART
var myPiechart = new Piechart({
  canvas: myCanvas,
  data: myData,
  //        red        orange     yellow     green      ADD more colors if needed
  colors: ["#FF0000", "#FFBC00", "#FFFF00", "#00FF00"],
});
myPiechart.draw();

// CLOCK PART
setInterval(setClock, 1000);

const hourHand = document.querySelector("[data-hour-hand]");
const minuteHand = document.querySelector("[data-minute-hand]");
const secondHand = document.querySelector("[data-second-hand]");

function setClock() {
  const currentDate = new Date();
  const secondsRatio = currentDate.getSeconds() / 60;
  const minutesRatio = (secondsRatio + currentDate.getMinutes()) / 60;
  const hoursRatio = (minutesRatio + currentDate.getHours()) / 12;
  setRotation(secondHand, secondsRatio);
  setRotation(minuteHand, minutesRatio);
  setRotation(hourHand, hoursRatio);
}

function setRotation(element, rotationRatio) {
  element.style.setProperty("--rotation", rotationRatio * 360);
}

setClock();

css file (clock):

.clock {
  width: 300px;
  height: 300px;
  /*background-image: url("piechart.png");  *//*HERE I WANT TO ADD PIECHART IMAGE*/
  border-radius: 50%;
  border: 2px solid black;
  position: relative;
}

.clock .number {
  --rotation: 0;
  position: absolute;
  width: 100%;
  height: 100%;
  text-align: center;
  transform: rotate(var(--rotation));
  font-size: 1.5rem;
}

.clock .hand {
  --rotation: 0;
  position: absolute;
  bottom: 50%;
  left: 50%;
  border: 1px solid white;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  transform-origin: bottom;
  z-index: 10;
  transform: translateX(-50%) rotate(calc(var(--rotation) * 1deg));
}

.clock::after {
  content: "";
  position: absolute;
  background-color: black;
  z-index: 11;
  width: 15px;
  height: 15px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 50%;
}

.clock .hand.second {
  width: 3px;
  height: 45%;
  background-color: red;
}

.clock .hand.minute {
  width: 7px;
  height: 40%;
  background-color: black;
}

.clock .hand.hour {
  width: 10px;
  height: 35%;
  background-color: black;
}

If there are better ways to do this I'm open to suggestions.

Place element canvas#myCanvas as a child of div.clock

  <div class="clock">
    <div class="hand hour" data-hour-hand></div>
    <div class="hand minute" data-minute-hand></div>
    <div class="hand second" data-second-hand></div>
    <canvas id="myCanvas"></canvas>
  </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM