Failed to execute ‘drawImage’ on ‘CanvasRenderingContext2D Trying to convert a canvas into image

I am having an issue creating an image of a canvas and translating it onto another canvas. The end goal is to create a loupe magnifier for a cgm viewer/editor, but I’m stuck on this issue. Here is an example.

HTML: 

<canvas id="canvas" width=240 height=240 style="background-color: aqua; 
left:0;right:0;margin:auto;z-index:1;margin-top:0px;">
</canvas>
<canvas id="canvas1" width=240 height=240 style="background-color:#808080;">
</canvas>
<p></p>
<a id="download"  href="" onclick="draw_image();">Download to myImage.jpg</a>

JS:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ox = canvas.width / 2;
var oy = canvas.height / 2;
ctx.font = "42px serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#800";
ctx.fillRect(ox / 2, oy / 2, ox, oy);

draw_image = function() {
let canvas1 = document.getElementById('canvas1') 
var image = canvas1.toDataURL("image/png")
let ctx1 = canvas1.getContext("2d");


ctx.drawImage(image, 0, 0)
};

(SVG path) What algorithm do I need to use to implement the transform machanism like illustrator transform tool

I’m making a tool that uses the SVG path to create different shapes and I need to resize them by dragging from 8 handles. In the Illustrator, shapes created by the pen tool can be transformed this way (draw.io uses the same resize technique I think). I also want to implement the same. Please, help me to learn the algorithm so that I can implement this mechanism on my own.

JavaScript If and else statement w/function calls not producing expected result

I have a mobile menu that includes four list items. When you click on the “Features” list item, another unordered list is supposed to populate below it, and when you click it again, it’s supposed to close it.

Here’s my issue:

Inside the addEventListener function, I am calling two other functions (displayType and displayTypeCheck) inside the if, and else statement. When I do this and click on the “Features” list item, it opens but does not close when I click it again.

If I don’t use the displayType and displayTypeCheck functions in the if and else statement and click on the “Features” list item, the UL will both open and close.

Why does the if and else statement that calls the other two functions not work, and how do I get it to work?

In the provided Javascript code below, the if and else statement that’s commented out works, and the block that’s not commented out is the code that doesn’t entirely work.

const menuIcon = document.querySelector(".mobile-menu-icon");
const mobileMenu = document.querySelector(".mobile-menu");
const closeMenuIcon = document.querySelector(".close-menu-icon");
const featuresMobile = document.querySelector(".features-mobile");
const featuresMobileDropdown = document.querySelector(".features-mobile-dropdown");
const overlay = document.querySelector(".overlay");


function displayType(element, displayValue) {
  element.style.display = displayValue;
}

function displayTypeCheck(element, displayValue) {
  element.style.display === displayValue;
}



menuIcon.addEventListener("click", function () {
  displayType(mobileMenu, 'block');
  displayType(overlay, 'block');
});

closeMenuIcon.addEventListener("click", function () {
  displayType(mobileMenu, 'none');
  displayType(overlay, 'none');
});



featuresMobile.addEventListener("click", function () {
    //   if (featuresMobileDropdown.style.display === "block") {
    //   featuresMobileDropdown.style.display = "none";
    // } else {
    //   featuresMobileDropdown.style.display = "block";
    // }

  if (displayTypeCheck(featuresMobileDropdown, "block")) {
    displayType(featuresMobileDropdown, "none");
  } else {
    displayType(featuresMobileDropdown, "block");
  }
});
@import url("https://fonts.googleapis.com/css2?family=Epilogue:wght@500;700&display=swap");

:root {
  --almostWhite: hsl(0, 0%, 98%);
  --mediumGray: hsl(0, 0%, 41%);
  --almostBlack: hsl(0, 0%, 8%);
  --navDropDownColor: #e9ecef;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

ul {
  list-style: none;
}

body {
  min-height: 100vh;
  font-family: "Epilogue", sans-serif;
  background-color: var(--almostWhite);
}

header {
  padding: .9375rem 2.5rem .9375rem 2.5rem;
  max-width: 100rem;
  margin: auto;
}

header nav {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

header nav ul li {
  cursor: pointer;
}


.register {
  border: .125rem solid var(--mediumGray);
  padding: .625rem .9375rem;
  border-radius: .8125rem;
}

.mobile-menu-icon {
  height: 3.125rem;
}


  .mobile-menu-icon {
    display: block;
    cursor: pointer;
  }

  .mobile-menu .mobile-nav-links {
    margin-top: 4.375em;
    padding-left: .9375em;
    color: var(--mediumGray);
  }

  .mobile-menu ul li {
    padding: .625em;
  }

  .mobile-menu .mobile-nav-links li ul {
    margin-left: .625em;
    margin-top: .625em;
    display: none;
  }

  .mobile-menu {
    background-color: white;
    width: 18.75em;
    height: 100vh;
    position: absolute;
    top: 0;
    right: 0;
    z-index: 2;
    display: none;
  }

  .close-menu-icon {
    margin-left: auto;
    margin-right: 1.25em;
    margin-top: 1.25em;
    display: block;
    cursor: pointer;
    height: 3.125em;
  }

  .login-register-mobile-container {
    color: var(--mediumGray);
    width: 90%;
    margin: 3.125em auto;
  }

  .login-register-mobile-container span {
    display: block;
    text-align: center;
    cursor: pointer;
  }

  .login-register-mobile-container span:first-child {
    margin-bottom: 1.25em;
  }
  
  
   .overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.6);
    backdrop-filter: blur(.1875rem);
    z-index: 1;
    display: none;
  }
<header>
      <nav>
        <img class="mobile-menu-icon" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Hamburger_icon.svg/2048px-Hamburger_icon.svg.png" alt="" />
        <div class="mobile-menu">
          <img
            class="close-menu-icon"
            src="https://cdn4.iconfinder.com/data/icons/user-interface-131/32/close-512.png"
            alt=""
          />
          <ul class="mobile-nav-links">
            <li class="features-mobile">Features
              <ul class="features-mobile-dropdown">
                <li>Todo List</li>
                <li>Calenders</li>
                <li>Reminders</li>
                <li>Planning</li>
              </ul>
            </li>
            <li class="company-mobile">Company</li>
            <li>Careers</li>
            <li>About</li>
          </ul>
          <div class="login-register-mobile-container">
            <span class="login">Login</span>
            <span class="register">Register</span>
          </div>
        </div>
      </nav>
      <div class="overlay"></div>
    </header>

Generating Hash JavaScript and HTML. Problems with innerHTML

Why does this doesn’t work for the innerHTML while it works perfectly fine when printing it on console.log()?

const hashTable = document.getElementById("hashTable");
const myString = document.getElementById("typeText");
const hashButton = document.getElementById("hash-btn");

const myArray = [];

// Convert to 32bit integer
function stringToHash(string) {
  var hash = 0;

  if (string.length == 0) return hash;

  for (i = 0; i < string.length; i++) {
    char = string.charCodeAt(i);
    hash = (hash << 5) - hash + char;
    hash = hash & hash;
  }

  return hash;
}

hashButton.addEventListener("click", () => {
  const string = myString.value;

  myArray.push(string);

  myArray.forEach((element) => {
    console.log(stringToHash(element), element);
    hashTable.innerHTML = `
  <tr>
      <th scope="row">${stringToHash(element)}</th>
      <td>${element}</td>
  </tr>
  
  `;
  });
});
  <body>
    <div class="container animate__animated animate__slideInRight">
      <!-- Navbar -->
      <!-- Navbar -->
      <h1 class="mt-5 mb-5 display-2 text-center">Hash Table</h1>
      <div class="form-outline">
        <input type="text" id="typeText" class="form-control" />
        <label class="form-label" for="typeText">String</label>
      </div>
      <div class="d-grid gap-2 my-4">
        <button class="btn btn-primary" id="hash-btn" type="button">
          Generate Hash
        </button>
      </div>
      <div class="table-responsive mt-5">
        <table class="table table-striped table-hover table-bordered">
          <thead>
            <tr>
              <th scope="col">#</th>
              <th scope="col">String</th>
            </tr>
          </thead>
          <tbody id="hashTable"></tbody>
        </table>
      </div>
    </div>
    <!-- MDB -->
    <script
      type="text/javascript"
      src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.0.0/mdb.min.js"
    ></script>
    <script src="HashTable.js"></script>
  </body>

As you can see, it only generates one tr.

null is not an object (evaluating ‘RCTVideoInstance.Contants’)’ with react native video

I’m Getting an error when importing and rendering the <Video /> Component from ‘react-native-video’

My code seems to be fine but heres it anyways:

import { View, Text, Dimensions } from 'react-native';
import React from 'react';
import Video from 'react-native-video';

const Player = () => {
  return (
    <View>
      <Video 
      source={{
        uri: "https://youtu.be/WSJHAsnot54"
      }}
      style={{
        height: 100,
        width: Dimensions.get("window").width
      }}
      
      />
    </View>
  )
}

export default Player;

The error i am getting while rendering:

null is not an object (evaluating 'RCTVideoInstance.Constants')

In JavaScript, can I prevent the onmouseup event from being triggered, replacing it with my own event?

I’m creating a slider widget to let me manage ranges of values, and have most of it complete.

Here is a demo of it: https://jsfiddle.net/d1wqb63a/

I want to set it up to actually trigger an onmouseup event when the mouse is released, with additional data in it. That is working, except that it is now triggers the onmouseup twice. Once directly by the browser and once by my code.

You can see that in the jsfiddle demo above. The output to the console is “undefined” when called by the normal event, and some actual data when called by mine, as it’s trying to access the custom info I added.

Here’s what I’m doing to trigger the event:

var e = new Event('mouseup');
e.sliderValues = JSON.parse(JSON.stringify(config.values));
element.dispatchEvent(e);

What I don’t know is how to disable the already triggered event; i.e, stop the browser from triggering the actual onmouseup event despite my adding the onmouseup callback. Is that even doable?

Creating scrollbars in an HTML PaperJS canvas element for use with paper.view.zoom

  • We have a PaperJS canvas that is set to 100% width/height
  • Users can zoom and pan
  • Users can add content to the canvas at various places within the canvas regardless of zoom/pan state
  • We want to add scrollbars to the canvas like those used in Figma when there is content outside the currently viewable area

When a user zooms in/out or pans with a PaperJS canvas, they’re not moving the actual canvas in the DOM or increasing the canvas element’s size. Instead, they’re changing the viewing relationship to content within the canvas element.

Thus the scrollbars need to be created in the canvas element but there doesn’t appear to be a way to lock the scrollbars ratio. For example, if the scrollbars are in the canvas context and you zoom in, you’re zooming on all of the canvas content and the scrollbars change in size as well. It seems like the only solution would be to have some sort of listener in place that always sets their size, position, etc in relation to the zoom/pan state of the canvas, which seems like a lot of extra code. Has anyone come across a solution for this?

React Native – How to reload colors based on Dark Mode and Light Mode

We have been trying to implement dark mode in an old project, where we have some colors defined in a separate file and been used throughout the application something like mentioned below

import {Appearance} from "react-native";

const isDarkMode = (Appearance.getColorScheme() === 'dark') ? true : false

const Color = {
    WHITE: '#FFFFFF',
    TRANSPARENT: 'transparent',
    THEMECOLOR: isDarkMode ? '#1A252F' : '#25A31D',
    THEMEBLACK: isDarkMode ? '#121B24' : '#252525',
    THEMEDARKGREEN: isDarkMode ? '#2F3F4D' : '#407F2C',
    THEMEWHITE: isDarkMode ? '#121B24' : '#FFFFFF',
    TXTGREETING: isDarkMode ? '#898989' : 'rgba(0, 0, 0, .5)',
    TXTWHITE: isDarkMode ? '#8A8A8A' : '#FFFFFF',
    TXTTHEME: isDarkMode ? '#676C69' : '#25A31D',
    TXTGREY: isDarkMode ? '#676C69' : '#9E9E9E',
    TXTDARKGREY: isDarkMode ? '#505050' : '#9E9E9E',
    TXTBLACK: isDarkMode ? '#676c69' : '#252525',
}

export default { Color };

It is used as shown below

import appColors from "common/colors";

export default StyleSheet.create({
    container:{
        flex:1,
        backgroundColor: appColors.Color.THEMECOLOR,
    }
});

We don’t have any internal feature to switch to the Dark Mode inside the app, but it should work if changed from Device settings, which does work well but it requires killing the app and restarting.

It doesn’t work when the app is running, though we have tried to infuse themes in NavigationContainer

import { NavigationContainer,DarkTheme,DefaultTheme } from "@react-navigation/native";
render() {
    return (
      <NavigationContainer theme={isDarkMode?DarkTheme:DefaultTheme}>
        <RootStackScreen screenProps={this.props} />
      </NavigationContainer>
    )
}

How to achieve this when the app is running and the Dark Mode is changed from device settings?

Thanks for any pointers.

unable to get document.querySelector to work on react

I am porting an old project written in HTML/CSS to react. one of the things I am unable to get to work properly is document.querySelector I am not sure if they work differently with react or if there is a better way to do it

For example the code block below does not seem to work not matter what I do

export default function AnimatedTabBar() {
  const list = document.querySelectorAll(".list");

  function activeList() {
    list.forEach((element) => element.classList.remove("active"));
    this.classList.add("active");
  }

  list.forEach((element) => element.addEventListener("click", activeList));


How to make the elevator move floors when pushing multiple buttons and sorting them constantly to the nearest floor?

I’m working on a elevator simulator in React JS with typescript. It’s quite simple, there are 6 buttons on every floor for the 6 floors to go to the chosen floor. And when you click on one of the buttons the color changes so you know it’s activated.

Here is the code for the floors

const handleClickButton = (floorNumber: number) => {
    setClickedButtons((oldVal: any) => [...oldVal, floorNumber]);
  };

  return (
    <div className="numberBtnsContainer">
      {floors.map((floor: Floor) => {
        const floorNumber = floor.floorNum;
        return (
          <p
            onClick={() => {
              handleClickButton(floorNumber);
            }}
            className={
              clickedButtons.includes(floorNumber)
                ? "floorNumber include"
                : "floorNumber"
            }
          >
            {floor.floorNum}
          </p>
        );
      })}
    </div>
  );

Question:
So now I need to have when you click on multiple buttons at the same time that the elevator changes floors like an normal elevator For example, when the elevator is on the fifth floor and you press the buttons 0, 1, and 3 in this order, the elevator must recognize that the most efficient order to stop is 3 -> 1 -> 0. And that it has a delay everytime it moves to a different floor. How would I go about that?

Forbidden (CSRF token missing or incorrect.): /audio

i have website with button to upload audio mp3 on a post. the problem, when i clicked the button, it’s open new / (http://localhost:8000/audio) actually just http://localhost:8000. and when i see terimal, there’s error message

Forbidden (CSRF token missing or incorrect.): /audio

at the same time, there’s error at my website with error message

Forbidden (403) CSRF verification failed. Request aborted.

Help Reason given for failure:

CSRF token missing or incorrect.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used
correctly. For POST forms, you need to ensure:

Your browser is accepting cookies. The view function passes a request
to the template’s render method. In the template, there is a {%
csrf_token %} template tag inside each POST form that targets an
internal URL. If you are not using CsrfViewMiddleware, then you must
use csrf_protect on any views that use the csrf_token template tag, as
well as those that accept the POST data. The form has a valid CSRF
token. After logging in in another browser tab or hitting the back
button after a login, you may need to reload the page with the form,
because the token is rotated after a login. You’re seeing the help
section of this page because you have DEBUG = True in your Django
settings file. Change that to False, and only the initial error
message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

what i want is, i can upload file song mp3 with django without database (just local). and the song can be defined by information such as artist, duration, genre, etc.

and here’s my code:

urls.py
from django.contrib import admin
from django.conf.urls import url
from . import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import path, re_path
from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^decode/$', views.decode),
    url(r'^$', views.homepage),
    path('audio', views.Audio_store),
]

urlpatterns += staticfiles_urlpatterns()

views.py:

from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import ensure_csrf_cookie
from subprocess import call
from django.core.files import File
from django.views.decorators.csrf import csrf_exempt
import subprocess
from MusicLockApp.forms import AudioForm

@ensure_csrf_cookie
def homepage(request):
    # return HttpResponse('homepage')
    return render(request, 'homepage.html')

def decode(request):
    # return HttpResponse('about')
    return render(request, 'decode.html')

    #@csrf_exempt
def obfuscate(request):
    print("HI")
    if request.method == 'GET':
        return HttpResponse("Hi")

    if request.method == 'POST':
        print("files: " + str(request.FILES))
        print("posts: " + str(request.POST))

        if len(request.POST) > 0:
            handle_uploaded_file(request.FILES['audio_file'])

    return HttpResponse("The form was valid!")

def handle_uploaded_file(f):
    with open('temp.mp3', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

    subprocess.check_call("ffmpeg -y -i temp.mp3 temp.wav", shell=True)

def Audio_store(request):
    if request.method == 'POST':
        form = AudioForm(request.POST, request.FILES or None)
        if form.is_valid():
            form.save()
            return HttpResponse('SUKSES BRUH')
    else:
        form = AudioForm()
    return render(request, 'homepage.html', {'form' : form})

models.py:

from django import forms
from django.db import models

class Audio_store(models.Model):
    record=models.FileField(upload_to='media/mp3')
    class Meta:
        db_table='Audio_store'

forms.py:

from django import forms 
from MusicLockApp.models import *

class AudioForm(forms.ModelForm):
    class Meta:
        model=Audio_store
        fields=['record']

add settings.py:

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'assets'),
)

MEDIA_URL = '/mp3/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'mp3')

homepage.html script:

<script>
        var file = undefined;
        var audio_formats = ["mp3"];
        
        // using jQuery
        function getCookie(name) {
          var cookieValue = null;
        
          if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
              var cookie = jQuery.trim(cookies[i]);
              // Does this cookie string begin with the name we want?
              if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
              }
            }
          }
        
          return cookieValue;
        }
        
        function fileAdded() {
          var x = document.getElementById("audio-file");
          file = x.files[0];
          var msg = document.getElementById("message");
        
          if (file != undefined) {
            x = file.name.split(".");
            var ext = x[x.length - 1];
        
            if (audio_formats.indexOf(ext) == -1) {
              msg.innerHTML = ext + " is not an audio file!";
            } else {
              msg.innerHTML = file.name + " has been successfully added!";
            }
          } else {
            msg.innerHTML = "Please select an audio file to obfuscate!";
          }
        }
        
        function obfuscate() {
          if (file == undefined)
            alert("Choose an audio file!");
          else {
            var obfuscateButton = document.getElementById("obfuscate-button");
            obfuscateButton.innerHTML = "Proccessing...";
            var xhr = new XMLHttpRequest();
            var url = "http://127.0.0.1:8000/obfuscator/obfuscate/";
            var method = 'POST';
            xhr.onreadystatechange = function() {
              if(xhr.readyState === 4 && xhr.status === 200) {
                  obfuscateButton.innerHTML = "Done!"
              }
            }
            xhr.open(method, url, true);
        
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
        
            var formData = new FormData();
            formData.append("audio_file", file);
            formData.append("file_name", file.name)
            xhr.send(formData);
          }
        }
        </script>

.dsnupload {
    background-color: #fbc786;
    color: white;
    text-align: center;
    font-weight: bold;
    padding: 20px;
}

.dsnupload:hover {
    background-color: #c88f5c;
    color: white;
    font-weight: bold;
    text-align: center;
}
<div class="row" style="margin-right: 10px;">
                            <form action="audio" method="post" enctype="multipart/form-data">
                            {% csrf_token %^}
                            {{ form }}
                            <button type="submit" class="dsnupload" id="audio-file" onchange="fileAdded()">
                                <i class="large material-icons" style="font-size: 50pt; margin-top: 10px;">audiotrack</i>
                                <p style="font-weight: bold; color: white;">Insert file audio (mp3)</p>
                            </button>
                            <p id="message"></p>
                            </form>
                        </div>

Sorting a javascript array based on another array element with different length [duplicate]

I have an array like this:

mainArray =[ [ "apple", 5, "AB" ], [ "banana", 6, "CD" ], [ "orange", 2, "BA" ], [ "Coconut", 7, "AB" ] , [ "Grapes", 1, "CD" ]]

sortArray = ['CD', 'AB' , 'BA']

I want to sort the “mainArray” based on “sortArray” values. So that the sorted array is :

[ [ "banana", 6, "CD" ], [ "Grapes", 1, "CD" ], [ "apple", 5, "AB" ], [ "Coconut", 7, "AB" ] , [ "orange", 2, "BA" ]]

How can I do this?

Thanks in advance

Is there a way to export paginated table as CSV file in Flask?

I would to export data from paginated table as CSV file in my Flask app. How could I do that?
I’m able to download only the first page.

function download_table_as_csv(table_id, separator = ',') {
    var rows = document.querySelectorAll('table#' + table_id + ' tr');
    var csv = [];
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll('td, th');
        for (var j = 0; j < cols.length; j++) {
            var data = cols[j].innerText.replace(/(rn|n|r)/gm, '').replace(/(ss)/gm, ' ')
            data = data.replace(/"/g, '""');
            row.push('"' + data + '"');
        }
        csv.push(row.join(separator));
    }
    var csv_string = csv.join('n');
    var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
    var link = document.createElement('a');
    link.style.display = 'none';
    link.setAttribute('target', '_blank');
    link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

Thanks in advance to everyone